package com.cnspt.repository;

import com.cnspt.models.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.PostConstruct;
import java.util.Map;

@Repository
public class RedisRepositoryImpl implements RedisRepository{
    private static final String KEY = "users";

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    private HashOperations<String, Integer, Users> hashOperations;

    @Autowired
    public RedisRepositoryImpl(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @PostConstruct
    private void init() {
        hashOperations = redisTemplate.opsForHash();
    }
    public Users find(final Integer id) {
        return (Users) hashOperations.get(KEY, id);
    }
    public Map<Integer, Users> findAll() {
        return hashOperations.entries(KEY);
    }
    public void save(final Users user) { hashOperations.put(KEY, user.getId(), user); }
    public void update(final Users user) {
        hashOperations.put(KEY, user.getId(), user);
    }
    public void delete(final Integer id) {
        hashOperations.delete(KEY, id);
    }

}
